package com.didispace.hystrix;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
public class HystrixCollapserUserController {

    private final Logger logger = Logger.getLogger(getClass());

    @Autowired
    private DiscoveryClient client;

    // 根据 id 返回 User 对象的 GET 请求接口    p168
    @RequestMapping(value = "/find/{id}", method = RequestMethod.GET)
    public User find(@PathVariable("id") Long id) {
        ServiceInstance instance = client.getLocalServiceInstance();
        logger.info("/user1, host:" + instance.getHost() + ", service_id:" + instance.getServiceId());
        return new User(id, "name0"+id, (int) (20+id));
    }

    // 根据 ids 返回 User 对象列表的 GET 请求接口，其中 ids 为以逗号分隔的 id 集合    p168
    @RequestMapping(value = "/findAll", method = RequestMethod.GET)
    public List<User> findAll(@RequestParam("ids") String ids){
        String[] split = ids.split(",");
        List<User> userList = new ArrayList<>();
        for (String s : split) {
            User user = new User();
            user.setId(Long.valueOf(s));
            user.setName("name0"+s);
            user.setAge(20+Integer.valueOf(s));
            userList.add(user);
        }
        return userList;
    }
}
